package com.lishui.wateroj.aspect;

import com.lishui.wateroj.annotation.AuthCheck;
import com.lishui.wateroj.contant.MessageConstant;
import com.lishui.wateroj.exception.PermissionException;
import com.lishui.wateroj.model.enumeration.UserRoleEnum;
import com.lishui.wateroj.model.pojo.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.lishui.wateroj.service.UserService;

import javax.annotation.Resource;

@Aspect
@Component
@Order(2)
public class AuthInterceptorAspect {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        Integer mustRole = authCheck.mustRole();
        // 当前登录用户
        UserVO loginUser = userService.getCurrentUser();
        // 必须有该权限才通过
        if (mustRole != -1) {
            UserRoleEnum mustUserRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
            if (mustUserRoleEnum == null) {
                throw new PermissionException(MessageConstant.MISSING_ADMINISTRATOR_RIGHTS);
            }
            Integer userRole = loginUser.getUserRole();
            // 如果被封号，直接拒绝
            if (UserRoleEnum.BAN.equals(mustUserRoleEnum)) {
                throw new PermissionException(MessageConstant.MISSING_ADMINISTRATOR_RIGHTS);
            }
            // 必须有管理员权限
            if (UserRoleEnum.ADMIN.equals(mustUserRoleEnum)) {
                if (!mustRole.equals(userRole)) {
                    throw new PermissionException(MessageConstant.MISSING_ADMINISTRATOR_RIGHTS);
                }
            }
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}